<template>
	<view class="container">
		<!-- 控制栏 -->
		<view class="control-bar">
			<picker mode="selector" :range="mapOptions" @change="filterByMap">
				<view class="picker">地图: {{ selectedMap || '全部' }}</view>
			</picker>
			<view class="current-group-name">
				{{currentGroupName}}[{{bosses.length}}]
			</view>
			<view class="sound-control" @click="toggleMute">
				<text>{{ isMuted ? '🔇 静音' : '🔊 声音' }}</text>
			</view>
		</view>

		<!-- BOSS列表 -->
		<scroll-view class="boss-list" scroll-y @scrolltolower="loadMoreBosses">
			<boss-card v-for="boss in visibleBosses" :key="boss.id" :boss="boss" @update="updateBossRefreshTime"
				@edit="handleEdit" @delete="handleDelete" @refreshed="handleBossRefreshed"
				@toggle-notification="handleToggleNotification" />
		</scroll-view>
		<!-- 新增导入确认弹窗 -->
		<import-confirm-popup ref="importConfirm" @merge="handleImportMerge" @create="handleImportCreate" />
		<!-- 分组列表弹窗-->
		<group-popup ref="groupList" @singleMerge="handleSingleMerge" @create="handleCreateGroup"
			@edit="handleEditGroup" @batchDelete="handleBatchDeleteGroup" @merge="handleMergeGroup"
			@delete="handleDeleteGroup" @itemClick="handleItemClick"></group-popup>
		<!-- 添加BOSS弹窗 -->
		<boss-form ref="bossForm" @submit="handleFormSubmit" />
		<!-- 菜单按钮 -->
		<fab-menu :fab-items="fabItems" @action="handleFabClick"></fab-menu>
		<!-- 添加BOSS按钮 -->
		<view class="add-btn" @click="showAddDialog">
			<uni-icons type="plus" size="24" color="#fff"></uni-icons>
		</view>
	</view>
</template>

<script>
	import defaultBosses from "./default-bosses.js"
	const MAX_BOSS_COUNT = 30;

	export default {
		data() {
			return {
				visibleCount: 5,
				selectedMap: '',
				currentGroupIndex: 0,
				currentGroupName: '默认分组',
				bosses: [],
				fabMenuOpen: false,
				isMuted: true,
				fabItems: [{
						icon: 'redo',
						color: '#00b894',
						action: 'share'
					}, // 绿色 - 分享(示例)
					{
						icon: 'list',
						color: '#0055ff',
						action: 'list'
					}, // 蓝色 - 列表
					{
						icon: 'trash',
						color: '#ff5a5f',
						action: 'clear'
					}, // 红色 - 清空
					// {
					// 	icon: 'gear',
					// 	color: '#6c5ce7',
					// 	action: 'setting'
					// } // 紫色 - 设置
				],
				player: null,
				tempData: [],
				groupList: [],
				isVibrating: false
			}
		},
		computed: {
			mapOptions() {
				return ['全部', ...new Set(this.bosses.map(b => b.map))];
			},
			filteredBosses() {
				let list = this.bosses
				if (this.selectedMap && this.selectedMap !== '全部') {
					list = list.filter(b => b.map === this.selectedMap);
				}
				return this.sortBosses(list)
			},
			visibleBosses() {
				return this.filteredBosses.slice(0, this.visibleCount);
			}
		},
		watch: {
			currentGroupIndex(val) {
				uni.setStorageSync('currentGroupIndex', val)
				this.currentGroupName = this.groupList[val].name
			}
		},
		onLoad(query) {
			if (query.data) {
				try {
					const decodedData = decodeURIComponent(query.data);
					const bossData = JSON.parse(decodedData);
					this.tempData = bossData;
					console.log('接收到的BOSS数据:', bossData);
				} catch (e) {
					console.error('数据解析失败:', e);
				}
			}
			this.loadData()
		},
		onShow() {
			// 页面加载时保持屏幕常亮
			uni.setKeepScreenOn({
				keepScreenOn: true
			})
		},
		onHide() {
			// 页面卸载时取消保持常亮
			uni.setKeepScreenOn({
				keepScreenOn: false
			})
		},
		onShareAppMessage() {
			const bossData = this.bosses;
			// 将对象转为Base64编码字符串
			const dataStr = JSON.stringify(bossData);
			const encodedData = encodeURIComponent(dataStr);

			return {
				title: `来自您的好友分享的BOSS刷新时间`,
				path: `/pages/index/index?data=${encodedData}`
			}
		},
		mounted() {
			if (this.tempData && this.tempData.length > 0) {
				this.showImportConfirm()
			}
		},
		methods: {
			showImportConfirm() {
				this.$refs.importConfirm.open();
			},
			// 处理分享数据合并
			handleImportMerge() {
				this.$refs.groupList.openForSingleMerge(this.groupList);
			},
			handleSingleMerge(index) {
				const targetGroup = this.groupList[index];
				if (!targetGroup) return;

				// 更新分组数据
				this.groupList[index].data = this.margeGroup(targetGroup.data, [this.tempData]);
				this.handleItemClick(index)
				// 保存数据
				this.saveData();
				this.$refs.importConfirm.close();
				// 显示合并结果
				uni.showToast({
					title: "数据合并完成",
					icon: 'success'
				});

				// 清空临时数据
				this.tempData = [];
			},
			handleImportCreate() {
				uni.showModal({
					title: '新建分组',
					content: '',
					placeholderText: '请输入分组名称',
					editable: true,
					success: (res) => {
						if (res.confirm && res.content) {
							if (res.content === '默认分组') {
								uni.showToast({
									title: '不能使用"默认分组"作为名称',
									icon: 'none'
								});
								return;
							}
							const hasName = this.groupList.some(item =>
								item.name === res.content
							);
							if (hasName) {
								uni.showToast({
									title: `[${res.content}]分组名称已存在，请换个名称`,
									icon: 'none'
								});
								return;
							}
							// 创建新分组并导入数据
							const newGroup = {
								name: res.content,
								data: this.tempData
							};
							this.groupList.push(newGroup);
							this.saveData()
							uni.showModal({
								title: '分组创建成功',
								content: '是否立即查看？',
								success: (res) => {
									if (res.confirm) {
										this.handleItemClick(this.groupList.length - 1)
									}
								}
							});
							this.tempData = []
							this.$refs.importConfirm.close()
						}
					}
				});
			},
			//切换分组
			handleItemClick(index) {
				if (index >= this.groupList.length) return;
				this.currentGroupIndex = index
				this.bosses = this.groupList[index].data
			},
			//创建分组
			handleCreateGroup(name) {
				const newGroup = {
					name: name,
					data: []
				};
				this.groupList.push(newGroup);
				this.saveData()
			},
			handleEditGroup({
				index,
				name
			}) {
				this.groupList[index].name = name
				if (index == this.currentGroupIndex) {
					this.currentGroupName = name
				}
				this.saveData()
			},
			handleMergeGroup(ids) {
				const targetGroupIndex = ids[0];
				const targetGroup = this.groupList[targetGroupIndex];
				const mergedData = [];
				// 遍历所有被合并的分组
				for (let i = 1; i < ids.length; i++) {
					const groupIndex = ids[i];
					const group = this.groupList[groupIndex];
					mergedData.push(group.data)
				}

				// 更新分组数据
				this.groupList[targetGroupIndex].data = this.margeGroup(targetGroup.data, mergedData);
				// 删除其他被合并的分组（保留目标分组）
				const groupsToDelete = ids.slice(1).sort((a, b) => b - a);
				for (const index of groupsToDelete) {
					this.groupList.splice(index, 1);
				}
				// 更新当前分组索引
				const newIndex = this.groupList.findIndex(item => item.name == targetGroup.name)

				this.handleItemClick(newIndex)
				// 保存数据
				this.saveData();

				uni.showToast({
					title: '分组合并完成',
					icon: 'success'
				});
			},
			margeGroup(target, data) {
				const mergedData = [...target]
				for (let i = 0; i < data.length; i++) {
					data[i].forEach(boss => {
						const existingIndex = mergedData.findIndex(
							b => b.name === boss.name && b.map === boss.map
						);
						if (existingIndex >= 0) {
							mergedData[existingIndex] = boss;
						} else {
							mergedData.push(boss);
						}
					})
				}
				return mergedData;
			},
			handleDeleteGroup(index) {
				this.groupList.splice(index, 1);

				// 调整当前分组索引
				let newIndex = 0
				if (this.currentGroupIndex != index) {
					newIndex = this.groupList.findIndex(item => item.name == this.currentGroupName)
				}
				this.handleItemClick(newIndex)

				// 保存数据
				this.saveData();

				uni.showToast({
					title: '分组删除成功',
					icon: 'success'
				});
			},
			handleBatchDeleteGroup(ids) {
				// 从大到小排序索引，以便正确删除
				const sortedIndices = [...ids].sort((a, b) => b - a);

				// 批量删除分组
				for (const index of sortedIndices) {
					this.groupList.splice(index, 1);
				}

				// 调整当前分组索引
				let newIndex = 0
				if (!ids.includes(this.currentGroupIndex)) {
					newIndex = this.groupList.findIndex(item => item.name == this.currentGroupName)
				}
				this.handleItemClick(newIndex)
				// 保存数据
				this.saveData();

				uni.showToast({
					title: `已删除${ids.length}个分组`,
					icon: 'success'
				});
			},
			// 保存数据
			saveData() {
				this.groupList[this.currentGroupIndex].data = this.bosses
				uni.setStorageSync('groupList', this.groupList)
			},
			//加载数据
			loadData() {
				const groupList = uni.getStorageSync('groupList') || defaultBosses
				const index = uni.getStorageSync('currentGroupIndex') || 0
				this.isMuted = uni.getStorageSync('isMuted')
				this.groupList = groupList
				if (groupList.length > 0) {
					this.bosses = groupList[index].data
					this.currentGroupIndex = index
					this.currentGroupName = groupList[index].name
				}
			},
			sortBosses(list) {
				return list.sort((a, b) => b.isNotify - a.isNotify);
			},
			//播放提醒声音
			playAlertSound(duration = 3612) {
				if (this.player) return;
				this.player = uni.createInnerAudioContext();
				this.player.src = '/static/sounds/alert.mp3';
				this.player.loop = true
				this.player.play()
				setTimeout(() => {
					this.player.destroy()
					this.player = null
				}, duration)
			},
			// 地图筛选
			filterByMap(e) {
				const index = e.detail.value;
				this.selectedMap = this.mapOptions[index];
			}, // 切换静音
			toggleMute() {
				this.isMuted = !this.isMuted;
				if (!this.isMuted) {
					this.playAlertSound(1806)
					this.startVibration(1806);
				} else {
					this.startVibration(1806);
				}
				uni.setStorageSync('isMuted', this.isMuted)
			},
			// 显示添加对话框
			showAddDialog() {
				if (this.bosses.length >= MAX_BOSS_COUNT) {
					uni.showToast({
						title: `最多添加${MAX_BOSS_COUNT}个BOSS`,
						icon: 'none'
					});
					return;
				}
				this.$refs.bossForm.openWithData(null);
			},
			//处理菜单点击
			handleFabClick(action) {
				switch (action) {
					case 'list':
						this.$refs.groupList.open(this.groupList)
						break
					case 'clear':
						this.showClearConfirm()
						break
					case 'setting':
						break
				}
			},
			showClearConfirm() {
				uni.showModal({
					title: '清空所有BOSS数据',
					content: '确定要清空所有BOSS数据吗？',
					success: (res) => {
						if (res.confirm) {
							this.bosses = []
							this.groupList[this.currentGroupIndex].data = []
							this.saveData();
							uni.showToast({
								title: '数据已清空',
								icon: 'success'
							});
						}
					}
				});
			},
			// 表单提交处理
			handleFormSubmit(data) {
				const {
					isEdit,
					bossData
				} = data
				if (isEdit) {
					const index = this.bosses.findIndex(b => b.id === bossData.id);
					if (index >= 0) {
						this.bosses.splice(index, 1, bossData);
						uni.showToast({
							title: '修改成功',
							icon: 'success'
						});
					}
				} else {
					this.bosses.unshift(bossData);
					uni.showToast({
						title: '添加成功',
						icon: 'success'
					});
				}
				this.saveData();
			},
			// 加载更多BOSS
			loadMoreBosses() {
				if (this.visibleCount < this.filteredBosses.length) {
					this.visibleCount = Math.min(
						this.visibleCount + 5,
						this.filteredBosses.length
					);
				}
			},
			// 切换提醒状态
			handleToggleNotification({
				bossId,
				enabled
			}) {
				const index = this.bosses.findIndex(b => b.id === bossId);
				if (index >= 0) {
					this.bosses[index].isNotify = enabled;
					this.saveData();
					uni.showToast({
						title: `已${enabled ? '开启' : '关闭'}提醒`,
						icon: 'none'
					});
				}
			},
			//更新boss刷新时间
			updateBossRefreshTime(bossId, deviation = 0) {
				const index = this.bosses.findIndex(b => b.id === bossId);
				if (index >= 0) {
					this.bosses[index].lastTime = Date.now() + deviation;
					this.saveData();
				}
			},
			// 编辑BOSS
			handleEdit(bossId) {
				const boss = this.bosses.find(b => b.id === bossId);
				if (boss) {
					this.$refs.bossForm.openWithData(boss);
				}
			},
			// 删除BOSS
			handleDelete(bossId) {
				this.bosses = this.bosses.filter(b => b.id !== bossId);
				this.saveData();
				uni.showToast({
					title: '删除成功',
					icon: 'success'
				});
			},
			// BOSS刷新处理
			handleBossRefreshed(bossId) {
				this.updateBossRefreshTime(bossId, 1000)
				const boss = this.bosses.find(b => b.id === bossId);
				uni.showToast({
					title: `"${boss.map}"的[${boss.name}]已刷新`,
					icon: "none",
					duration: 3000
				});
				if (!this.isMuted) {
					//播放提示声音
					this.playAlertSound(3612);
					this.startVibration(3612);
				} else {
					//振动
					this.startVibration(3612);
				}
			},
			startVibration(duration) {
				if (this.isVibrating) return;

				this.isVibrating = true;
				const interval = 400; // 每次震动间隔(ms)
				let remaining = duration;

				const vibrate = () => {
					if (remaining <= 0) {
						this.stopVibration();
						return;
					}
					wx.vibrateLong();
					remaining -= interval;
					this.vibrationTimer = setTimeout(vibrate, interval);
				};
				vibrate();
			},
			// 停止震动
			stopVibration() {
				if (this.vibrationTimer) {
					clearTimeout(this.vibrationTimer);
					this.vibrationTimer = null;
				}
				this.isVibrating = false;
			},
		}
	}
</script>

<style lang="scss">
	/* 样式保持不变 */
	.container {
		padding: 15px;
		background-color: #f5f5f5;

		.boss-list {
			height: calc(100vh - var(--window-top) - var(--status-bar-height) - var(--window-bottom) - 80px - 52px);
		}

		.add-btn {
			position: fixed;
			right: 20px;
			bottom: 20px;
			width: 52px;
			height: 52px;
			border-radius: 50%;
			background-color: #007aff;
			display: flex;
			align-items: center;
			justify-content: center;
			box-shadow: 0 4px 8px rgba(0, 122, 255, 0.3);
		}

		.control-bar {
			display: flex;
			justify-content: space-between;
			align-items: center;
			padding: 10px 15px;
			background-color: #fff;
			border-radius: 8px;
			margin-bottom: 15px;
			box-shadow: 0 2px 6px rgba(0, 0, 0, 0.05);
			height: 30px;
			color: #333;
		}

		.current-group-name {
			color: #007aff;
		}

		.picker {
			padding: 5px 10px;
			border-radius: 4px;
			background-color: #f8f8f8;
		}

		.sound-control {
			padding: 5px 10px;
			border-radius: 4px;
			background-color: #f8f8f8;
		}
	}
</style>